package com.example.vw.platformintegration;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private WebView mWebTable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });


        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        loadTable();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    private void loadTable(){
        mWebTable = (WebView) findViewById(R.id.web_table);
    
        mWebTable.setWebViewClient(new myWebClient());
        mWebTable.setWebChromeClient(new myChromeClient());
        
                                       WebSettings settings = mWebTable.getSettings();
        settings.setDisplayZoomControls(false); //隐藏webview缩放按钮
        //支持javascript
        settings.setJavaScriptEnabled(true);
    
        settings.setAllowContentAccess(true);
        // 设置可以支持缩放
        settings.setSupportZoom(false);
        // 设置出现缩放工具
        settings.setBuiltInZoomControls(false);
        //扩大比例的缩放
        settings.setUseWideViewPort(true);
        settings.setDomStorageEnabled(true);
//        settings.setDatabaseEnabled(true);
//        settings.setAppCacheEnabled(true);
        //自适应屏幕
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setDefaultTextEncodingName("utf-8");
        settings.setLoadWithOverviewMode(true);
        settings.setNeedInitialFocus(true);
        settings.setLoadsImagesAutomatically(true);//自动加载图片
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setSupportMultipleWindows(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);

        mWebTable.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        mWebTable.setHorizontalScrollBarEnabled(true);
        mWebTable.setInitialScale(100);
        /**
         * edited by lzy
         * 20180103
         * 登陆页面修改
         */
        // mLoginView.setWebChromeClient(new CustomChromeClient("androidapi", LoginScope.class));
//        mWebTable.addJavascriptInterface(new LoginScopeVW(mLoginView),"androidapi");

        try {
            if (Build.VERSION.SDK_INT >= 16) {
                Class<?> clazz = mWebTable.getSettings().getClass();
                Method method = clazz.getMethod(
                        "setAllowUniversalAccessFromFileURLs", boolean.class);
                if (method != null) {
                    method.invoke(mWebTable.getSettings(), true);
                }
            }
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        
        
//        String url = "http://60.205.224.13:8080/VUE/dist/index.html";
//        String url = "file:///android_asset/tj_new/appdemo.html";
//        String url = "https://cn.bing.com/search?q=%E6%AD%BB%E7%A5%9E&qs=n&form=QBLH&sp=-1&pq=%E6%AD%BB%E7%A5%9E&sc=8-2&sk=&cvid=5A819FF69CE84CD49848F60DEE556EF4";
//        String url = "https://cn.bing.com";
// String url = "https://www.baidu.com/";
//        String url = "http://211.103.218.91:8095";
//	    String url = "http://122.224.94.108:8005";
        String url = "http://211.103.218.91:8095/appdemo.html?table=1538235454853&catalogID=510122106200001&year=2018&period=4&userID=278_1";
//        String url ="https://cn.bing.com/search?q=%E6%AD%BB%E7%A5%9E&qs=n&form=QBLH&sp=-1&pq=%E6%AD%BB%E7%A5%9E&sc=8-2&sk=&cvid=5A819FF69CE84CD49848F60DEE556EF)";
	    mWebTable.loadUrl(url);
    }

//    protected void onResume(){
//        super.onResume();
//        mWebTable.post(new Runnable() {
//            @Override
//            public void run() {
//                mWebTable.evaluateJavascript("javascript:load(\"1538235454853\", \"510122106200001\", \"2018\", \"4\", \"278_1\")",null);
//            }
//        });
//    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
    
    class myWebClient extends WebViewClient {
        
        
        @Override
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view, url);
            Log.v("tag", "url = " + url);
        }
        
        @Override
        public void onReceivedError(WebView view, int errorCode,
                                    String description, String failingUrl) {
            Log.e("tag","errorCode = "+errorCode);
            super.onReceivedError(view, errorCode, description, failingUrl);
        }
        
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {//webview页面加载开始时就会执行此方法、一般用作重定向时的初始化工作
            super.onPageStarted(view, url, favicon);
        }
        
        /**
         * url重定向会执行此方法以及点击页面某些链接也会执行此方法
         *
         * @param view
         *            当前webview
         * @param url
         *            即将重定向的url
         * @return true:表示当前url已经加载完成，即使url还会重定向都不会再进行加载 false 表示此url默认由系统处理，该重定向还是重定向，直到加载完成
         */
        /*@Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            
            *//*if (!Tools.urlCheck(url)) {
                return true;
            }
            if (!TextUtils.isEmpty(url) && url.endsWith("apk")) {
                Intent viewIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(viewIntent);
            } else {
                if (!MainActivity.this.processCustomUrl(WebActivity.this, url, null, false)) {
                    url = MainActivity.this.addCookie2Url(WebActivity.this, url);
                    // view.loadUrl(url);//（步骤一）
                    // return true;//（步骤二）
                } else {
                    return true;
                }
            }
            Logcat.dLog("url loading = " + url);
            return *//*
            return super.shouldOverrideUrlLoading(view, url);//（步骤三）
        }*/
        
        @Override
        public void onPageFinished(WebView view, String url) {//
            
            super.onPageFinished(view, url);
        }
        
    }
    
    class myChromeClient extends WebChromeClient {
    
        
        @Override
        public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
            super.onShowCustomView(view, callback);
            Log.e("tag", "on Show Custom View >>>>>webView");
            
        }
        
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            
            MainActivity.this.setTitle("网页加载中……");
            MainActivity.this.setProgress(newProgress*100);
            if(newProgress == 100){
                MainActivity.this.setTitle(R.string.app_name);
            }
        }
        
    }
    
    
}


